# -*- coding: utf-8 -*- 
'''
Created on 2 sept. 2012

@author: Olivier
'''

import threading            # Import threading module
from ServerClientDataTreatment import ServerClientDataTreatment
import pickle

class ServerClientTreatment(threading.Thread):
    '''
    List commands:
    -> 
    '''

    def __init__(self, inClient, inAdresse, inServer):
        '''
        Constructor
        '''
        threading.Thread.__init__(self)
        
        self.__mClient = inClient
        self.__mAdresse = inAdresse
        self.__mServer = inServer
        self.__mStopServerClientTreatment = False
        
        #start this thread
        self.start()

    def run(self):
        self.__mStopServerClientTreatment = False
        print 'Got connection from', self.__mAdresse
        self.Send('InitYourself')
        while not self.__mStopServerClientTreatment:
            try:
                theData = self.Received()
                if theData:
                    ServerClientDataTreatment(self, theData) #Treatment of the received data
                elif theData is None:
                    break
            except:
                print "Error"
                
        self.Close()  
            
    def Stop(self):
        '''
        Function to stop the client and send Bye bye before leave it
        '''
        self.__mStopServerClientTreatment = True
        self.__mServer.RemoveServerClientTreatment(self)
        
            
    def Close(self):
        '''
        Function to close the client socket
        '''
        if self.__mClient is None: return
        self.__mClient.close()  # Close the connection
        
        
    def Send(self, inObject):
        '''
        function to send a object (or string) to the client
        '''
        if self.__mClient is None: return
        self.__mClient.send(pickle.dumps(inObject))
        
    def Received(self):
        '''
        function to receive an object or a string
        '''
        if self.__mClient is None: return
        theObject = pickle.loads(self.__mClient.recv(1024))
        return theObject
        
        
    def stop(self):
        '''
        Stop the thread
        '''
        self.__mStopServerClientTreatment = True
        
    def GetServer(self):
        return self.__mServer
    